<template>
  <div class="search-container">
    <form class="search-form" action="/">
      <!-- show-action的作用是显示右边取消的按钮的 -->
      <van-search v-model="searchText" background="#3296fa" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" @focus="isResultShow=false" />
    </form>

    <!-- 搜索结果 -->
    <SearchResult :searchText="searchText" v-if="isResultShow"></SearchResult>
    <!-- 联想建议 -->
    <SearchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearch"></SearchSuggestion>
    <!-- 搜索历史 -->
    <SearchHistory :searchHistories="secrchHistories" @clear-search-history="secrchHistories=[]" @search="onSearch" @delete-search-item="update" v-else></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggection.vue'
import { setItem, getItem } from '@/utils/storage.js'

export default {
  name: 'SearchIndex',
  data() {
    return {
      searchText: '',
      isResultShow: false,
      secrchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 搜索的历史记录
    }
  },
  watch: {
    secrchHistories(value) {
      // console.log('haha')
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }
  },
  methods: {
    // val 是搜索框里面输入的内容
    onSearch(val) {
      // console.log(val)
      // 更新文本框内容
      this.searchText = val
      // 存储搜索历史记录
      // 要求 不要有重复历史记录 最新的排在最前面
      const index = this.secrchHistories.indexOf(val) // 判断数组里面是否有val 如果有 则返回它的索引 若果没有则返回-1
      if (index !== -1) {
        // 说明有重复的
        // 把重复的移除掉 然后在添加进去
        this.secrchHistories.splice(index, 1)
      }
      this.secrchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    },
    update(index) {
      this.secrchHistories.splice(index, 1)
    }
  },
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2;
  }
}
</style>
